package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author:ZhouXin
 * @Date:2022/10/25 22:38
 * @Description:
 **/
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    ILoginService loginService;

    @Autowired
    IKaptchaService iKaptchaService;

    /**
     * 用户登录
     * 生成cookie
     *
     * @param map
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResponseData postLogin(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        try {
            String userName = map.get("userName");
            String userPwd = map.get("userPwd");
            String captcha = map.get("captcha");

            //验证码校验，老师已经帮我们实现
            KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();

            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    if ("kaptcha_uuid".equals(cookie.getName())){
                        String uuid = cookie.getValue();
                        kaptchaCodeRequest.setUuid(uuid);
                    }
                }
            }
            kaptchaCodeRequest.setCode(captcha);
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);


            //验证用户名和密码
            UserLoginRequest userLoginRequest = new UserLoginRequest();
            userLoginRequest.setUserName(userName);
            userLoginRequest.setUserPwd(userPwd);
            //userLoginRequest.setCaptcha(captcha);
            UserLoginResponse login = loginService.login(userLoginRequest);

            //获取邮件
            String email = login.getEmail();
            //对邮件做判断，若邮件不为空，则说明用户名和密码正确
            if (!StringUtils.isEmpty(email)) {
                //进来说明说明验证用户名和密码成功
                //TODO return之前，生成cookie
                //从客户端中获取cookie信息
                //Cookie[] cookies = request.getCookies();

                //生成新的cookie
                Cookie access_token = new Cookie("access_token", login.getToken());
                //设置路径
                access_token.setPath("/");
                //cookie返回客户端
                response.addCookie(access_token);
                return new ResponseUtil<>().setData(login);
            }
        } catch (Exception e) {
            //登录失败
            e.printStackTrace();
            return new ResponseUtil<>().setErrorMsg(e.getMessage());
        }
        return null;
    }

    /**
     * 验证用户是否登录
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request, HttpServletResponse response) {
        String userInfo = request.getHeader("user_info");
        Object object = JSON.parse(userInfo);
        return new ResponseUtil<>().setData(object);
    }


    /**
     * 用户退出
     * 根据cookie的存活时间进行退出
     * 还需要保持cookie的path进行一致
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("access_token".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return new ResponseUtil<>().setData(null, "success");
    }
}
